package com.msk.common.utils.sign;

import com.msk.common.utils.Digests;
import com.msk.common.utils.Encodes;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description
 * @Author zlf
 * @Date 2023/5/8 17:23
 */
public class MskPasswordEncoder implements PasswordEncoder {

    public static final String HASH_ALGORITHM = "SHA-1";

    public static final int HASH_INTERATIONS = 1024;

    public static final int SALT_SIZE = 8;

    /**
     * 密码加密
     * @param rawPassword
     * @return
     */
    @Override
    public String encode(CharSequence rawPassword) {
        String plainPassword = rawPassword.toString();
        String plain = Encodes.unescapeHtml(plainPassword);
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

    /**
     * 密码验证
     * @param rawPassword 明文密码
     * @param encodedPassword 密文密码
     * @return 验证成功返回true
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String plainPassword = rawPassword.toString();
        String plain = Encodes.unescapeHtml(plainPassword);
        byte[] salt = Encodes.decodeHex(encodedPassword.substring(0, 16));
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return encodedPassword.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
    }
}
